/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.domain.*;
import me.zhengjie.repository.FzChunkRepository;
import me.zhengjie.repository.FzFilesRepository;
import me.zhengjie.repository.OrderTechnologyRepository;
import me.zhengjie.service.FzOrdersService;
import me.zhengjie.service.dto.FzOrdersDto;
import me.zhengjie.service.dto.FzOrdersQueryCriteria;
import me.zhengjie.service.mapstruct.FzOrdersMapper;
import me.zhengjie.util.FileUtils;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.FzOrdersRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zcc
* @date 2021-05-16
**/
@Service
@RequiredArgsConstructor
public class FzOrdersServiceImpl implements FzOrdersService {

    private final FzOrdersRepository fzOrdersRepository;
    private final FzOrdersMapper fzOrdersMapper;
    private final OrderTechnologyRepository orderTechnologyRepository;
    private final FzFilesRepository fzFilesRepository;
    private final FzChunkRepository fzChunkRepository;

    @Value("${file.windows.path}")
    private String uploadFolder;

    @Override
    public Map<String,Object> queryAll(FzOrdersQueryCriteria criteria, Pageable pageable){
        Page<FzOrders> page = fzOrdersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fzOrdersMapper::toDto));
    }

    @Override
    public List<FzOrdersDto> queryAll(FzOrdersQueryCriteria criteria){
        return fzOrdersMapper.toDto(fzOrdersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public FzOrdersDto findById(String orderId) {
        FzOrders fzOrders = fzOrdersRepository.findById(orderId).orElseGet(FzOrders::new);
        ValidationUtil.isNull(fzOrders.getOrderId(),"FzOrders","orderId",orderId);
        return fzOrdersMapper.toDto(fzOrders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FzOrdersDto create(FzOrders resources) {
//        resources.setOrderId(IdUtil.simpleUUID());
        return fzOrdersMapper.toDto(fzOrdersRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FzOrders resources) {
        FzOrders fzOrders = fzOrdersRepository.findById(resources.getOrderId()).orElseGet(FzOrders::new);
        ValidationUtil.isNull( fzOrders.getOrderId(),"FzOrders","id",resources.getOrderId());
        fzOrders.copy(resources);
        fzOrdersRepository.save(fzOrders);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String orderId : ids) {
            fzOrdersRepository.deleteById(orderId);
            List<OrderTechnology> list = orderTechnologyRepository.findByOrderId(orderId);
            orderTechnologyRepository.deleteAll(list);

            List<ErpFiles> files = fzFilesRepository.findBybid(orderId);
            fzFilesRepository.deleteAll(files);

            List<ErpChunk> chunks = fzChunkRepository.findBybid(orderId);
            fzChunkRepository.deleteAll(chunks);

            String sourcePath = uploadFolder + SecurityUtils.getCurrentUsername() + File.separator + orderId;
            FileUtils.deleteDir(new File(sourcePath));
        }
    }

    @Override
    public void download(List<FzOrdersDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FzOrdersDto fzOrders : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名称", fzOrders.getFileName());
            map.put("日期", fzOrders.getDateTime());
            map.put("客户", fzOrders.getCustomer());
            map.put("类别", fzOrders.getTypes());
            map.put("菲林", fzOrders.getFeilin());
            map.put("模具", fzOrders.getModel());
            map.put("备注", fzOrders.getRemark());
            map.put("针数", fzOrders.getNeedleNum());
            map.put("行数", fzOrders.getSampleRows());
            map.put("单片时间", fzOrders.getSingleChipTime());
            map.put("单片重量", fzOrders.getWeight());
            map.put("烫机温度", fzOrders.getScaldTemp());
            map.put("烫机速度", fzOrders.getScaldSpeed());
            map.put("烫机压力", fzOrders.getScaldPre());
            map.put("订单数量", fzOrders.getOrderTechnologyId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
